import utils from './../utils'
import * as types from '../constants/address'
import store from 'store'

//获取全球国家列表
export const getCountry =(data,config={})=>{
	data= {...data,...{func:'region-wd-country'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			if(res.code == 200)
				{config.callback && config.callback(res.data)}
			
		})
	}
}
//英文版国家的地区列表
export const getRegion =(data,config={})=>{
	data= {...data,...{func:'region-wd-region'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			if(res.code == 200)
				{config.callback && config.callback(res.data)}
			
		})
	}
}
//英文版国家的地区列表
export const getCity =(data,config={})=>{
	data= {...data,...{func:'region-wd-city'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			if(res.code == 200)
				{config.callback && config.callback(res.data)}
			
		})
	}
}

//地址列表
export const getAddressList =(data,config={})=>{
	data= {...data,...{func:'addr-recv-list'}}
    return (dispatch,getState)=>{
    	let options = getState().addressList.toJS()
    	if(config.isCache && options.length >0){
    		return dispatch({type:types.GET_ADDRESS_LIST,data:options})
    	}
		return utils.form(utils.url.index,data)
		.then(res=>{
			return dispatch({type:types.GET_ADDRESS_LIST,data:res.data||[]})
		})
	}
}

//添加地址
export const addAddress =(data,config={})=>{
	data= {...data,...{func:'addr-recv-add'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			config.callback && config.callback(res)
		})
	}
}

//修改地址
export const updateAddress =(data,config={})=>{
	data= {...data,...{func:'addr-recv-edit'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			config.callback && config.callback(res)
		})
	}
}

//删除地址
export const delAddress =(data,config={})=>{
	data= {...data,...{func:'addr-recv-del'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			let options = getState().addressList.toJS()
			options=options.filter(item => item.addr_id != data.addr_id);
			return dispatch({type:types.GET_ADDRESS_LIST,data:options||[]})
			
		})
	}
}

//根据id 修改地址列表
export const updateAddressChecked =(data,config={})=>{
    return (dispatch,getState)=>{
		let options = getState().addressList.toJS()
		options.map ( item =>{
			if(item.addr_id == data.addr_id)
			 item.checked = true
			else
			 item.checked =false
		})
		return dispatch({type:types.GET_ADDRESS_LIST,data:options||[]})
	}
}

//获取用户收货地址详情
export const getAddressInfo =(data,config={})=>{
	data= {...data,...{func:'addr-recv-info'}}
    return (dispatch,getState)=>{
		return utils.form(utils.url.index,data)
		.then(res=>{
			config.callback && config.callback(res)
		})
	}
}